package cn.oms.oms.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.oms.oms.entity.Appointment;
import cn.oms.oms.entity.Patient;
import cn.oms.oms.exception.ServiceException;
import cn.oms.oms.mapper.AppointmentMapper;
import cn.oms.oms.mapper.PatientMapper;
import cn.oms.oms.service.IAppointmentService;
import cn.oms.oms.utils.TimeTool;
import cn.oms.oms.vo.AppointmentVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AllenChen曾晨
 * @since 2022-04-29
 */
@Service
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, Appointment> implements IAppointmentService {

    @Autowired
    public AppointmentMapper appointmentMapper;

    @Autowired
    public PatientMapper patientMapper;

    /**
     * 查询预约挂号列表
     * @param appointmentVo
     * @return
     */
    @Override
    public PageInfo<Appointment> selectAppointmentList(AppointmentVo appointmentVo) {

        QueryWrapper<Patient> query = new QueryWrapper<>();
        // 根据患者名称查询患者信息
        if (StringUtil.isNotEmpty(appointmentVo.getPatientName())){
            query.like("patientName",appointmentVo.getPatientName());
        }
        // 删除 条件查询
        query.eq("deleteFlag",0);
        // 查询患者
        List<Patient> patientList = patientMapper.selectList(query);

        QueryWrapper<Appointment> query1 = new QueryWrapper<>();
        //查询单个患者

        // 获取患者ID列表
        List<Integer> patientIdList = new ArrayList<>();

        if (patientList.size()>0&&patientList!=null){
            for (Patient p:patientList) {
                patientIdList.add(p.getPatientId());
            }
        }
        // 条件查询 患者ID
        if (patientIdList.size()>0&&patientIdList!=null){
            if (appointmentVo.getPatientId()!=null&&!"".equals(appointmentVo.getPatientId())){
                query1.eq("patientId",appointmentVo.getPatientId());
            }else {
                query1.in("patientId",patientIdList);
            }
        }
        // 条件查询 预约时间
        if (StringUtil.isNotEmpty(appointmentVo.getAppointmentTime())){
            // 获取前端日期
            String date = appointmentVo.getAppointmentTime();
            // 05-04-2022
            // 转为正确格式
            date = TimeTool.formattingTime(date);
            System.out.println("date = " + date);
            Date simpleDate = new Date();
            try {
                simpleDate = new SimpleDateFormat("yyyy-MM-dd").parse(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("simpleDate = " + simpleDate);
            //日期格式转换
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(simpleDate);
            // 获取当天开始时间
            calendar.set(Calendar.HOUR_OF_DAY,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            Date startTime = calendar.getTime();
            System.out.println("startTime = " + startTime);
            String startTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime);
            System.out.println("startTimeStr = " + startTimeStr);
            // 获取当天结束时间
            calendar.set(Calendar.HOUR_OF_DAY,23);
            calendar.set(Calendar.MINUTE,59);
            calendar.set(Calendar.SECOND,59);
            Date endTime = calendar.getTime();
            System.out.println("endTime = " + endTime);
            String endTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime);
            System.out.println("endTimeStr = " + endTimeStr);
            // 加入条件判断查询语句
            query1.ge("appointmentStartTime",startTimeStr);
            query1.le("appointmentStartTime",endTimeStr);
        }
        // 条件查询 预约类型
        if(appointmentVo.getAppointmentType()!=null&&!appointmentVo.getAppointmentType().equals("")){
           if (appointmentVo.getAppointmentType()==3){

           }else {
               query1.eq("appointmentType",appointmentVo.getAppointmentType());
           }
        }
        // 条件查询 未删除
        query1.eq("deleteFlag",0);
        //分页
        PageHelper.startPage(appointmentVo.getPageNum(),appointmentVo.getPageSize());
        // 查询列表
        List<Appointment> appointmentList = appointmentMapper.selectList(query1);

        // 日期格式化
        for (Appointment appointment: appointmentList) {
            // 创建时间格式化
            String date =  new SimpleDateFormat("yyyy-MM-dd").format(appointment.getAppointmentStartTime());
            appointment.setReturnAppointmentStartTime(date);
            // 创建时间格式化
            date =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(appointment.getCreateTime());
            appointment.setReturnCreateTime(date);

            // 患者名称获取
            List<Patient> patientList1 = patientList.stream().filter(patient -> patient.getPatientId().equals(appointment.getPatientId())).collect(Collectors.toList());
            if (patientList1.size()>0&&patientList1!=null){
                appointment.setPatientName(patientList1.get(0).getPatientName());
            }
        }

        return new PageInfo<>(appointmentList);
    }

    /**
     * 查询患者详情
     * @param appointmentVo
     * @return
     */
    @Override
    public Appointment selectPatientDetail(AppointmentVo appointmentVo) {
        if (appointmentVo.getAppointmentId()==null||"".equals(appointmentVo.getAppointmentId())){
            throw new ServiceException("查询患者详情异常！！！！");
        }
        QueryWrapper<Appointment> query = new QueryWrapper<>();
        query.eq("appointmentId",appointmentVo.getAppointmentId());

        // 查询预约
        Appointment appointment = appointmentMapper.selectOne(query);
        if (appointment==null){
            throw new ServiceException("数据库查询异常！！！");
        }

        // 查询患者
        QueryWrapper<Patient> query1 = new QueryWrapper<>();
        query1.eq("patientId",appointment.getPatientId());
        query1.eq("deleteFlag",0);
        Patient patient = patientMapper.selectOne(query1);
        if (patient==null){
            throw new ServiceException("数据库查询异常！！！");
        }
        appointment.setPatientName(patient.getPatientName());

        // 预约类型参数
        if (appointment.getAppointmentType()==0){
            appointment.setAppointmentTypeName("门诊");
        }
        if (appointment.getAppointmentType()==1){
            appointment.setAppointmentTypeName("住院");
        }

        //日期格式化
        String date = new SimpleDateFormat("MM-dd-yyyy").format(appointment.getAppointmentStartTime());
        if (StringUtil.isEmpty(date)){
            throw new ServiceException("日期格式化失败");
        }
        appointment.setReturnAppointmentStartTime(date);

        return appointment;
    }

    /**
     * 新增预约挂号
     * @param appointmentVo
     * @return
     */
    @Override
    public String addAppointment(AppointmentVo appointmentVo) {
        if (appointmentVo.getPatientId()==null){
            throw new ServiceException("请选择患者！！！");
        }

        // 预约时间格式化
        String appointmentTime = appointmentVo.getAppointmentTime();
        // 将时间转格式
        String date = TimeTool.formattingTime(appointmentTime);
        Date dateTime = new Date();
        boolean formatStatus = false;
        try {
            dateTime = new SimpleDateFormat("yyyy-MM-dd").parse(date);
            formatStatus = true;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (!formatStatus){
            throw new ServiceException("日期格式化异常,日期格式错误");
        }

        QueryWrapper<Appointment> query = new QueryWrapper<>();
        query.eq("patientId",appointmentVo.getPatientId());

        // 查询 预约类型
        if (appointmentVo.getAppointmentType()!=null&&!appointmentVo.getAppointmentType().equals("")){
            query.eq("appointmentType",appointmentVo.getAppointmentType());
        }else {
            throw new ServiceException("请选择预约类型");
        }

        // 日期格式化
        if (StringUtil.isNotEmpty(date)){
            //日期格式转换
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateTime);

            // 获取当天开始时间
            calendar.set(Calendar.HOUR_OF_DAY,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            Date startTime = calendar.getTime();
            System.out.println("startTime = " + startTime);

            String startTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime);
            System.out.println("startTimeStr = " + startTimeStr);

            // 获取当天结束时间
            calendar.set(Calendar.HOUR_OF_DAY,23);
            calendar.set(Calendar.MINUTE,59);
            calendar.set(Calendar.SECOND,59);
            Date endTime = calendar.getTime();
            System.out.println("endTime = " + endTime);

            String endTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime);
            System.out.println("endTimeStr = " + endTimeStr);

            // 加入条件判断查询语句
            query.ge("appointmentStartTime",startTimeStr);
            query.le("appointmentStartTime",endTimeStr);
        }
        // 查询条件 预约标记和删除标记
        query.eq("appointmentFlag",0);
        query.eq("deleteFlag",0);

        // 查询当天是否有预约
        List<Appointment> appointments = appointmentMapper.selectList(query);
        if (appointments.size()>0){
            // 当前患者有预约了
            throw new ServiceException("患者今日已有预约");
        }

        // 若没有 则新增预约
        Appointment appointment = new Appointment();
        appointment.setPatientId(appointmentVo.getPatientId());
        appointment.setAppointmentType(appointmentVo.getAppointmentType());
        appointment.setAppointmentStartTime(dateTime);
        appointment.setAppointmentFlag(0);
        appointment.setCreateTime(new Date());
        appointment.setDeleteFlag(0);
        int num = appointmentMapper.insert(appointment);
        if (num!=1){
            throw new ServiceException("数据库新增异常！！！");
        }

        return "ok";
    }

    /**
     * 修改预约挂号
     * @param appointmentVo
     * @return
     */
    @Override
    public String updateAppointment(AppointmentVo appointmentVo) {

        if (appointmentVo.getAppointmentId()==null||"".equals(appointmentVo.getAppointmentId())){
            throw new ServiceException("参数异常，患者ID为空");
        }
        Appointment appointment = new Appointment();
        appointment.setAppointmentId(appointmentVo.getAppointmentId());

        if (appointmentVo.getAppointmentType()==null||"".equals(appointmentVo.getAppointmentType())){
            throw new ServiceException("参数异常，预约类型为空");
        }
        appointment.setAppointmentType(appointmentVo.getAppointmentType());

        // 预约时间格式化
        String appointmentTime = appointmentVo.getAppointmentTime();
        // 将时间转格式
        String date = TimeTool.formattingTime(appointmentTime);
        Date dateTime = new Date();
        boolean formatStatus = false;
        try {
            dateTime = new SimpleDateFormat("yyyy-MM-dd").parse(date);
            formatStatus = true;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (!formatStatus){
            throw new ServiceException("日期格式化异常,日期格式错误");
        }
        appointment.setAppointmentStartTime(dateTime);

        int num = appointmentMapper.updateById(appointment);

        if (num!=1){
            throw new ServiceException("数据库新增异常！！！");
        }

        return "ok";
    }

    /**
     * 删除预约挂号
     * @param id
     * @return
     */
    @Override
    public String deleteAppointment(Integer id) {
        if (id==null||"".equals(id)){
            throw new ServiceException("参数异常 未知的预约ID");
        }
        QueryWrapper<Appointment> query = new QueryWrapper<>();
        query.eq("appointmentId",id);
        Appointment appointment = appointmentMapper.selectOne(query);
        if (appointment==null){
            throw new ServiceException("未找到预约");
        }
        appointment.setDeleteFlag(1);
        int num = appointmentMapper.updateById(appointment);
        if (num!=1){
            throw new ServiceException("数据库新增异常！！！");
        }
        return "ok";
    }
}
